﻿using Digitalmes.Infrastructure.Net.Http;

namespace Digitalmes.Infrastructure;

internal static class NetServiceCollectionExtensions
{
    /// <summary>
    /// 注册 HTTP 客户端。
    /// </summary>
    /// <param name="services"></param>
    /// <param name="name"></param>
    /// <param name="baseUrl"></param>
    public static void AddResilienceHttpClientSetup(this IServiceCollection services, string name, string baseUrl)
    {
        services.AddHttpClient(name, client =>
        {
            client.BaseAddress = new Uri(baseUrl);
        })
        .AddStandardResilienceHandler(options =>
        {
            options.Retry.MaxRetryAttempts = 1;
            options.TotalRequestTimeout.Timeout = TimeSpan.FromSeconds(15); // 总的超时时间
            options.AttemptTimeout.Timeout = TimeSpan.FromSeconds(3); // 每次重试的超时时间
            options.CircuitBreaker.BreakDuration = TimeSpan.FromSeconds(5); // 熔断时间
        });
    }

    /// <summary>
    /// 注册 HTTP 客户端。
    /// </summary>
    /// <param name="services"></param>
    /// <param name="configuration">配置服务</param>
    /// <param name="configName">配置文件中的节点名称</param>
    /// <returns></returns>
    public static void AddResilienceHttpClientSetup(this IServiceCollection services, IConfiguration configuration, string configName = "RestHttp")
    {
        var options = configuration.GetSection(configName).Get<Dictionary<string, SimpleHttpEndpointOptions>>();
        if (options != null)
        {
            foreach (var (name, v) in options)
            {
                if (!string.IsNullOrEmpty(v.BaseUrl))
                {
                    services.AddResilienceHttpClientSetup(name, v.BaseUrl);
                }
            }
        }
    }
}
